package com.yidong.laidian.laidian.controller;

import com.yidong.laidian.laidian.dataobject.UsersDO;
import com.yidong.laidian.laidian.enums.ResultEnum;
import com.yidong.laidian.laidian.exception.ApiViewException;
import com.yidong.laidian.laidian.form.UserForm;
import com.yidong.laidian.laidian.service.UserService;
import com.yidong.laidian.laidian.util.ResultVoUtils;
import com.yidong.laidian.laidian.vo.Person;
import com.yidong.laidian.laidian.vo.ResultVO;
import com.yidong.laidian.laidian.vo.UserVo;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class IndexController {
    private final UserService userService;

    @GetMapping("/users/list")
    public ResultVO<Object> findAllUsers() {
        return ResultVoUtils.success(userService.getUserList());
    }

    @PostMapping("/users")
    public ResultVO<Object> createUserForm(@Valid @RequestBody UserForm userForm,
                                           BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            System.out.println("错误信息：");
            System.out.println(bindingResult.getFieldError().getDefaultMessage());

            throw new ApiViewException(ResultEnum.ACCOUNT_NOT_EXIST.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());

        }

        UsersDO usersDO = new UsersDO();
        usersDO.setName(userForm.getName());
        usersDO.setPassword(userForm.getPassword());
        usersDO.setEmail(userForm.getEmail());
        usersDO.setPhone(userForm.getPhone());
        usersDO.setAge(userForm.getAge());

        UsersDO save = userService.save(usersDO);

        return ResultVoUtils.success(userForm);
    }

    @GetMapping("/")
    public String index() {
        UserVo userVo = new UserVo();

        userVo.setName("laoliu");
        userVo.setAge(18);
        userVo.setSex("man");

        userVo.getSex();

        System.out.println(userVo.toString());

        Person person = new Person();
        person.setAge(20);

        System.out.println(person);

        return "index";
    }
}
